import 'package:flutter/material.dart';
import '../utils/G.dart';

class CartProvider with ChangeNotifier {
  List _cartList = []; // 购物车中的商品列表
  double _orderAmount = 0; // 订单金额
  int _total = 0; // 商品总数量
  bool _isAllChecked = true; // 是否全选

  List get cartList => _cartList;
  double get orderAmount => double.parse(_orderAmount.toStringAsFixed(2));
  int get total => _total;
  bool get isAllChecked => _isAllChecked;

  /// 初始化购物车
  void initCart(List list) {
    _cartList = list;

    computeCart();
  }

  void computeCart() {
    _orderAmount = 0;
    _total = 0;
    var n = 0;
    if (_cartList.length > 0) {
      _cartList.map((item) {
        if (item['attrStatus']) {
          _orderAmount += double.parse(item['truePrice']) * item['cart_num'];
          _total += item['cart_num'] as int;
          n++;
        }
      }).toList();

      // 是否全选
      _isAllChecked = _cartList.length == n ? true : false;
    }
  }

  /// 修改单个商品的选中状态
  void toggleCheckItem(Map cartItem, bool val) {
    _cartList.map((item) {
      // 判断传入的商品，是否被选中
      if (item['product_attr_unique'] == cartItem['product_attr_unique']) {
        item['attrStatus'] = val;
      }

      return item;
    }).toList();

    // 计算购物车
    computeCart();

    notifyListeners();
  }

  // 全选 | 全取消
  void toggleCheckAll(bool val) {
    print('all: ' + val.toString());
    _cartList.map((item) {
      item['attrStatus'] = val;
    }).toList();

    // 计算购物车
    computeCart();

    notifyListeners();
  }

  /// 递增
  void increment(Map item) {
    item['cart_num']++;

    G.api.cart.setNum(
        productId: item['product_id'],
        unique: item['product_attr_unique'],
        type: 1);

    computeCart();

    notifyListeners();
  }

  /// 递减
  void decrement(Map item) {
    if (item['cart_num'] > 1) {
      item['cart_num']--;

      G.api.cart.setNum(
          productId: item['product_id'],
          unique: item['product_attr_unique'],
          type: 0);
    }

    computeCart();

    notifyListeners();
  }

  void deleteCart() {
    // 收集 ids 参数
    String ids = "";
    _cartList.forEach((element) {
      if (element['attrStatus']) {
        ids += element['id'].toString() + ",";
      }
    });

    if (ids.isEmpty) {
      G.toast('请选择商品');
    } else {
      // ids = "1,2,3,"
      ids = ids.substring(0, ids.length - 1);

      // 执行删除
      G.api.cart.deleteFromCart(ids).then((value) {
        if (value) {
          // 删除成功
          _cartList.removeWhere((element) => element['attrStatus'] == true);
          G.success('删除成功');
          computeCart();
          notifyListeners();
        } else {
          G.error('删除失败');
        }
      });
    }
  }
}
